package com.tomcov.server;


import java.util.Arrays;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.tomcov.client.service.JourneyService;
import com.tomcov.shared.Journey;
import com.tomcov.shared.JourneyPassenger;

public class JourneyServiceImpl extends RemoteServiceServlet implements JourneyService{

	private static final long serialVersionUID = 1L;


	@Override
	public Journey AddJourney(Journey journey) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(com.tomcov.shared.Journey.class);
		query.declareImports("import java.util.Date");
		query.setFilter("Driver == FromParam && date == dateParam && Heuredep == HeuredepParam");
		query.declareParameters("String FromParam, Date dateParam, Date HeuredepParam");
		try{
			@SuppressWarnings("unchecked")
			List<Journey> results = (List<Journey>) query.execute(journey.getDriver(),journey.getDate(),journey.getHeuredep());
			if(results.size()==0)	
			{pm.makePersistent(journey);
			return journey;}
			else{
				return null;
			}
		}
		finally{
			query.closeAll();
			pm.close();
		}

	}

	public List<Journey> getJounreyAsDriver(String Username){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(com.tomcov.shared.Journey.class);
		query.setFilter("Driver == FromParam");
		query.declareParameters("String FromParam");
		try{
			@SuppressWarnings("unchecked")
			List<Journey> results = (List<Journey>) query.execute(Username);
			if(results.size()==0){
				return null;
			}
			else{
				return (List<Journey>) pm.detachCopyAll(results);
			}
		}
		finally{
			query.closeAll();
			pm.close();
		}
	}

	public Journey delete(Journey journey){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(com.tomcov.shared.Journey.class);
		query.declareImports("import java.util.Arrays");
		query.setFilter("id == FromParam && Driver == DriverParam");
		query.declareParameters("String FromParam, String DriverParam");

		try{
			@SuppressWarnings("unchecked")
			List<Journey> results = (List<Journey>) query.execute(journey.getId(),journey.getDriver());
			if(results.size()==0){
				return null;
			}
			else{
				Journey res= results.get(0);
				pm.deletePersistent(res);
				return res;
			}
		}
		finally{
			query.closeAll();
			pm.close();
		}
	}

	public Journey updatejourney(Journey toupdate,Journey updated){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Journey e = pm.getObjectById(com.tomcov.shared.Journey.class, toupdate.getId());
			e.setPassengerList(updated.getPassengerList());
			return updated;

		} finally {
			pm.close();
		}

	}

	public List<Journey> getJourneyasPassenger(String username){

		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(com.tomcov.shared.Journey.class);
		query.setFilter("nbpass != param");
		query.declareParameters("int param");

		try{
			@SuppressWarnings("unchecked")
			List<Journey> results = (List<Journey>) query.execute(0);
			if(results.size()==0){
				return null;
			}
			else{
				
				Journey[] list = new Journey[0];
				int h=0;
				for(Journey res : results){
					for(String res2 : res.getPassengerList()){
						if(res2==username){
							list[h]=res;
							h++;
						}
					}
				}
				return Arrays.asList(list);
			}
		}
		finally{
			query.closeAll();
			pm.close();
		}
	}

	@Override
	public Journey addpassenger(String idnumber, String passenger,String Waypoints) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Journey e = pm.getObjectById(com.tomcov.shared.Journey.class, idnumber);
			e.addPassenger(passenger);
			List<String> wp = e.getWaypoints();
			wp.add(Waypoints);
			e.setWaypoints(wp);
			Journey updated = e;
			return updated;

		} finally {
			pm.close();
		}

	}

	@Override
	public List<Journey> getJourneyAtTheDameDate(JourneyPassenger J) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(com.tomcov.shared.Journey.class);
		query.setFilter("Heuredep <= FromParam && date == ArrParam");
		query.declareImports("import java.util.Date");
		query.declareParameters("Date FromParam, Date ArrParam");
		try{
			@SuppressWarnings("unchecked")
			List<Journey> results = (List<Journey>) query.execute(J.getHeuredep(),J.getDate());
			if(results.size()==0){
				return null;
			}
			else{
				return (List<Journey>) pm.detachCopyAll(results);
			}
		}
		finally{
			query.closeAll();
			pm.close();
		}
	}

	public Journey setimage(byte[] c, String mapUrl,Journey j){
		return null;
		/*PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(com.tomcov.shared.Journey.class);
		query.setFilter("id == FromParam");
		query.declareParameters("String FromParam");

		try {
			@SuppressWarnings("unchecked")
			List<Journey> result1 = (List<Journey>) query.execute(j.getId());
			List<Journey> results = (List<Journey>) pm.detachCopyAll(result1);
			if(results!=null && results.size()!=0){
				Journey e= results.get(0);
				try{
					
					String imageId =  request.getParameter("imageId");
			         byte[] imageData = readImageDataFromDB(imageId);
			         response.setContentType("image/png");
			         response.getOutputStream().write(imageData,0,imageData.length);
					URLFetchService fetchService = URLFetchServiceFactory.getURLFetchService();

					HTTPResponse fetchResponse = fetchService.fetch(new URL(mapUrl));
					String fetchResponseContentType = null;
					for (HTTPHeader header : fetchResponse.getHeaders()) {
						if (header.getName().equalsIgnoreCase("content-type")) {
							fetchResponseContentType = header.getValue();
							break;
						}
					}
					if (fetchResponseContentType != null) {
						e.setTypeImage(fetchResponseContentType);
						e.setMapImage(fetchResponse.getContent());
						return e;
					}
					else{return null;}
					
				}

				catch (MalformedURLException er) {
					er.printStackTrace();
					return null;
				} 
				catch (IOException er) {
					er.printStackTrace();
					return null;
				}
			}
			else{
				return null;
			}
		}
		finally {
			pm.close();
		}*/
		
	}

	
	
	public Journey getJourneyById(String idnumber){

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Journey e = pm.getObjectById(com.tomcov.shared.Journey.class, idnumber);
			Journey updated = e;
			return updated;

		} finally {
			pm.close();
		}

	}

	@Override
	public Journey addpassenger(String idnumber, String passenger) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Journey e = pm.getObjectById(com.tomcov.shared.Journey.class, idnumber);
			e.addPassenger(passenger);
			Journey updated = e;
			return updated;

		} finally {
			pm.close();
		}

	}
	
	/*public String getImage(Journey J){
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(com.tomcov.shared.Journey.class);
		query.setFilter("id == FromParam && Driver == DriverParam");
		query.declareParameters("String FromParam, String DriverParam");
		try{
			@SuppressWarnings("unchecked")
			List<Journey> results = (List<Journey>) query.execute(J.getId(),J.getDriver());
			if(results.size()==0){
				return null;
			}
			else{
				byte[] cc = results.get(0).getMapImage();
				String base64 = Base64Utils.toBase64(cc);
			    base64 = "data:image/png;base64,"+base64; 
			    System.out.println(base64);
				return base64;
			}
		}
		finally{
			query.closeAll();
			pm.close();
		}
		
	}*/

	@Override
	public Journey getJourneyByIdandAddWaypoints(String[] c, String journeyidnumber,JourneyPassenger jp) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Journey e = pm.getObjectById(com.tomcov.shared.Journey.class, journeyidnumber);
			e.addPassenger(jp.getPassenger());
			
			List<String> wp = e.getWaypoints();
			wp.add(jp.getFrom());
			wp.add(jp.getTo());
			e.setWaypoints(wp);
			e.addPassenger(jp.getPassenger());
			
			Journey updated = e;
			return updated;

		} finally {
			pm.close();
		}
	}
	
	public Journey getJourneyByIdandAddWaypoints(String journeyidnumber,JourneyPassenger jp) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Journey e = pm.getObjectById(com.tomcov.shared.Journey.class, journeyidnumber);
			e.addPassenger(jp.getPassenger());
			
			List<String> wp = e.getWaypoints();
			
			wp.add(jp.getFrom());
			wp.add(jp.getTo());
			
			e.setWaypoints(wp);
			Journey updated = e;
			return updated;

		} finally {
			pm.close();
		}
	}

}

